import { type QueryPage as _QueryPage } from "~/types";

export class QueryPage<T = any> {
  page: number;
  pageSize: number;
  total?: number;
  params: T | undefined;

  constructor(page = 1, pageSize = 10, params?: T) {
    this.page = page;
    this.pageSize = pageSize;
    this.params = params;
  }

  set update(queryList: _QueryPage<T>) {
    const { page, pageSize, total } = queryList.pagenation;
    this.page = page;
    this.pageSize = pageSize;
    this.total = total;
  }

  set totalPage(total: number) {
    if (total < 0) {
      this.total = 0;
      return;
    }
    this.total = total;
  }
  get maxPage() {
    const { total, pageSize } = this;
    if (!total) {
      return 0;
    }
    return Math.ceil(total / pageSize);
  }
  nextPage() {
    const { page, maxPage } = this;
    if (page >= maxPage) {
      this.page = maxPage;
      return maxPage;
    }
    this.page = page + 1;
    return this.page;
  }
  get hasNext() {
    const { page, maxPage } = this;
    return page < maxPage;
  }

  reset() {
    this.page = 1;
    this.pageSize = 10;
    this.total = undefined;
  }
  prevPage() {
    const { page } = this;
    if (page <= 2) {
      this.page = 1;
      return 1;
    }
    this.page = page - 1;
    return this.page;
  }
  setParam(key: keyof T, value: any) {
    if (!this.params) {
      this.params = {} as T;
    }
    this.params[key] = value;
  }
  removeParam(key: keyof T) {
    if (!this.params) {
      return;
    }
    delete this.params[key];
  }
  get query() {
    const { page, pageSize, params } = this;
    return {
      page,
      pageSize,
      ...params,
    };
  }
  get queryUrl() {
    const { query } = this;
    const paramObj: { [key: string]: any } = {};
    for (const key in query) {
      if (Object.prototype.hasOwnProperty.call(query, key)) {
        const element = query[key as keyof typeof query];
        paramObj[key] = element?.toString();
      }
    }
    return new URLSearchParams(paramObj).toString();
  }
}
